﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Configuration;


namespace GloberoSport.Negocio
{
    public class ProcesarTrack
    {


        private static decimal obtVelocidad(string trkpt_id, DataTable pdtTrkPtExt)
        {
            string expression;
            expression = "trkpt_Id =" + trkpt_id;
            DataRow[] foundRows;

            decimal vel = 0;
            foundRows = pdtTrkPtExt.Select(expression);

            if (foundRows.Length > 0)
            {
                string sVelocidad = foundRows[0]["speed"].ToString().Replace(".", ",");
                vel = decimal.Parse(sVelocidad);
            }
            return vel;
        }
        public static string procesar(string sFile, string sUsuario)
        {
            string sRetorno = "";
            decimal distanciaGrabar = decimal.Parse(ConfigurationManager.AppSettings["DistanciaEntrePuntos"].ToString());//("0,5");
            int idTrack = -1;
            Negocio.Track tr = new Negocio.Track();
            tr.Autor = sUsuario;
            DataSet ds = new DataSet();
            ds.ReadXml(sFile);
            DataTable dtTrkPt = ds.Tables["trkpt"];
            DataTable dtTrkPtExt = ds.Tables["extensions"];
            DataTable dtMetadata = ds.Tables["metadata"];
            if (dtMetadata.Rows.Count == 1)
            {
                try
                {
                    tr.FechaIni = DateTime.Parse(dtMetadata.Rows[0]["time"].ToString());
                    tr.AltMax = 0;
                    tr.AltTotal = 0;
                    tr.Distancia = 0;
                    tr.TsTotal = 0;
                    tr.VelMax = 0;
                    tr.VelMedia = 0;
                    idTrack = tr.guardar();
                }
                catch (Exception ex)
                {
                }
            }
            if (idTrack != -1)
            {
                decimal altIni = 0;
                decimal latIni = 0;
                decimal lonIni = 0;
                decimal altPrev = 0;
                decimal latPrev = 0;
                decimal lonPrev = 0;
                decimal altPrevGrab = 0;
                decimal latPrevGrab = 0;
                decimal lonPrevGrab = 0;
                decimal altMax = 0;
                decimal altTot = 0;
                decimal velMax = 0;
                decimal velMed = 0;
                decimal distancia = 0;
                decimal distanciaPrevGrab = 0;
                int tiempototal = 0;
                dtTrkPt.DefaultView.Sort = "time asc";
                altIni = decimal.Parse(dtTrkPt.Rows[0]["ele"].ToString().Replace(".", ","));
                latIni = decimal.Parse(dtTrkPt.Rows[0]["lat"].ToString().Replace(".", ","));
                lonIni = decimal.Parse(dtTrkPt.Rows[0]["lon"].ToString().Replace(".", ","));
                altPrev = altIni;
                latPrev = latIni;
                lonPrev = lonIni;
                altPrevGrab = altIni;
                latPrevGrab = latIni;
                lonPrevGrab = lonIni;
                int iIndice = 0;
                TrackPoint tpPrev = new TrackPoint();
                TrackPoint tpPrevGuardado = new TrackPoint();
                tpPrev.EstadoCont = 0;
                foreach (DataRow dr in dtTrkPt.Rows)
                {
                    try
                    {
                        bool bGrabarPrevio = false;
                        bool bGrabarActual = false;
                        Negocio.TrackPoint tp = new Negocio.TrackPoint();
                        tp.TrackId = idTrack;
                        tp.Indice = iIndice;
                        tp.Altitud = decimal.Parse(dr["ele"].ToString().Replace(".", ","));
                        tp.Lat = decimal.Parse(dr["lat"].ToString().Replace(".", ","));
                        tp.Lon = decimal.Parse(dr["lon"].ToString().Replace(".", ","));
                        tp.Fecha = DateTime.Parse(dr["time"].ToString().Replace(".", ","));
                        tp.Velocidad = obtVelocidad(dr["trkpt_Id"].ToString(), dtTrkPtExt);
                        tp.Ref_desnPrev = 0;

                        decimal distanciaPrev = Negocio.Utilidades.CalculateDistanceBetweenGPSCoordinates(lonPrev, latPrev, tp.Lon, tp.Lat);
                        distancia += distanciaPrev;
                        distanciaPrevGrab += distanciaPrev;

                        tp.Ref_xOrigen = distancia;
                        tp.Ref_xPrev = distanciaPrevGrab;
                        TimeSpan ts1 = tp.Fecha - tr.FechaIni;
                        TimeSpan ts2 = tp.Fecha - tpPrevGuardado.Fecha;

                        tp.Ref_tsOrigen = (int)Math.Ceiling(ts1.TotalSeconds);
                        tiempototal = tp.Ref_tsOrigen;
                        tp.Ref_tsPrev =  (int)Math.Ceiling(ts2.TotalSeconds);
                        tp.Ref_desnPrev = 0;

                        //ESTABLECEMOS ALTITUD MAXIMA
                        if (altMax < tp.Altitud)
                        {
                            altMax = tp.Altitud;
                        }
                        //ACUMULAMOS ALTITUD
                        if (altPrev < tp.Altitud)
                        {
                            altTot += (tp.Altitud - altPrev);                            
                            tp.Estado = "UP";
                            if (tpPrev.Estado == "UP")
                                tp.EstadoCont = tpPrev.EstadoCont + 1;
                            else
                                tp.EstadoCont = 1;
                        }
                        if (altPrev > tp.Altitud)
                        {
                            tp.Estado = "DOWN";
                            if (tpPrev.Estado == "DOWN")
                                tp.EstadoCont = tpPrev.EstadoCont + 1;
                            else
                                tp.EstadoCont = 1;
                        }
                        altPrev = tp.Altitud;
                        latPrev = tp.Lat;
                        lonPrev = tp.Lon;
                        
                        iIndice++;

                        if (tpPrev.Id != -1)
                        {
                            if ((tpPrev.Altitud > tp.Altitud) && (tpPrev.Estado == "UP") && (tpPrev.EstadoCont > 4))
                                bGrabarPrevio = true;
                            if ((tpPrev.Altitud < tp.Altitud) && (tpPrev.Estado == "DOWN") && (tpPrev.EstadoCont > 4))
                                bGrabarPrevio = true;
                        }
                        
                        if ((distanciaPrevGrab >=distanciaGrabar) || (distancia == 0))
                        {
                            bGrabarActual = true;
                        }

                        // CONDICION PARA GRABAR
                        if (bGrabarActual)
                        {
                            try
                            {
                                tp.guardar();
                                distanciaPrevGrab = 0;
                                tpPrevGuardado = tp;
                            }
                            catch (Exception ex)
                            {
                            }
                        }


                        // CONDICION PARA GRABAR
                        if (bGrabarPrevio)
                        {
                            try
                            {
                                tpPrev.guardar();
                                tpPrevGuardado = tp;
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                        tpPrev = tp;
                        tpPrev.Id = 0;
                    }
                    catch (Exception ex)
                    {
                    }
                }
                tr.Id = idTrack;
                tr.Distancia = decimal.Parse(distancia.ToString().Split(new char[] { ',' })[0] + "," + distancia.ToString().Split(new char[] { ',' })[1].Substring(0, 2));
                tr.AltTotal = altTot;
                tr.AltMax = altMax;
                tr.TsTotal = tiempototal;
                tr.guardar();
                sRetorno = "Hoy he recorrido " + tr.Distancia + " Km. en " + tr.TsTotal/60 + " minutos.";
            }
            int i = 0;
            return sRetorno;
        }
    }
}

